package com.itheima.tcpdemo2;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class ServiceDemo {

    public static void main(String[] args) {
        try(
                //1.创建一个服务器端Socket，即SocketServer，指定绑定的端口，并监听此端口
                ServerSocket serverSocket = new ServerSocket(8888);
                ) {
            System.out.println("服务端启动成功！");
            //2.调用accept()方法开始监听，等待客户端的连接
            Socket socket = serverSocket.accept();

            //3.获取输入流，并读取客户端信息
            DataInputStream dis = new DataInputStream(socket.getInputStream());

            // 4.读取数据
            while (true) {
                // 如果客户端的端口关闭的话，就退出循环

                if(dis.available() > 0){
                    System.out.println("客户端说：" + dis.readUTF());
                    System.out.println("客户端的ip为：" + socket.getInetAddress());
                    System.out.println("客户端的端口为：" + socket.getPort());
                    System.out.println("------------------------------------------");
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
